#include "connection.h"
#include <QStringList>

OnetConnection::OnetConnection(QObject *parent) : QObject(parent)
{
    m_socket = new QTcpSocket(this);
    m_state = NotConnected;
    connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)),
            SLOT(onSocketError(QAbstractSocket::SocketError)));
    connect(m_socket, SIGNAL(connected()), SLOT(onConnected()));
    connect(m_socket, SIGNAL(aboutToClose()), SLOT(onAboutToClose()));
    connect(m_socket, SIGNAL(disconnected()), SLOT(onDisconnected()));
    connect(m_socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            SLOT(onStateChanged(QAbstractSocket::SocketState)));
    connect(m_socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
    connect(m_socket, SIGNAL(readChannelFinished()), SLOT(onReadChannelFinished()));
    connect(m_socket, SIGNAL(bytesWritten(qint64)), SLOT(onBytesWritten(qint64)));
}

OnetConnection::~OnetConnection()
{
    if(m_socket->isOpen())
        m_socket->close();
    delete m_socket;
}

bool OnetConnection::IsConnected()
{
    switch(m_state)
    {
    case Idle:
    case Sending:
    case Receiving:
        return m_socket->isOpen();
    default:
        return false;
    }
}

bool OnetConnection::IsActive()
{
    return m_state != NotConnected;
}

bool OnetConnection::OutgoingData()
{
    return m_outgoingData != 0;
}

void OnetConnection::Connect(QString aServerAddress, quint16 aServerPort)
{
    if(IsActive())
        return;
    m_socket->connectToHost(aServerAddress, aServerPort);
    m_state = Connecting;
}

void OnetConnection::Disconnect()
{
    if(!IsConnected())
        return;
    m_socket->disconnectFromHost();
    m_state = Disconnecting;
}

void OnetConnection::Send(QString aData)
{
    QByteArray arr = aData.toUtf8().append("\r\n", 2);
    m_outgoingData += arr.length();
    m_socket->write(arr);
}

void OnetConnection::onSocketError(QAbstractSocket::SocketError aError)
{
    emit ConnectionError((int)aError);
}

void OnetConnection::onConnected()
{
    m_state = Idle;
    emit Connected();
}

void OnetConnection::onDisconnected()
{
    m_state = NotConnected;
    emit Disconnected();
}

void OnetConnection::onBytesWritten(qint64 aBytes)
{
    m_outgoingData -= aBytes;
    emit DataSent(aBytes);
}

void OnetConnection::onStateChanged(QAbstractSocket::SocketState /*aState*/)
{
    // TODO: change state
}

void OnetConnection::onReadyRead()
{
    while(m_socket->canReadLine())
    {
        QString str = m_socket->readLine();
        emit DataReceived(str);
    }
}

void OnetConnection::onReadChannelFinished()
{
    // TODO
}

void OnetConnection::onAboutToClose()
{
    // TODO
}
